package com.takepoints.mobile;

import java.io.IOException;

import com.takepoints.android.bo.CustomerSiteInfo;
import com.takepoints.android.TPConst;
import com.takepoints.android.services.PublicServices;
import com.takepoints.android.services.TPServices;
import com.takepoints.android.vo.ReturnVal;
import com.takepoints.android.util.SecurityUtil;
import com.takepoints.android.util.StringUtil;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;

@TargetApi(10)
public class NfcCheckin extends BaseActivity {
	
	private static NfcAdapter mAdapter;
	private static PendingIntent mPendingIntent;
	private static IntentFilter[] mFilters;
	private static String[][] mTechLists;
	
	private final String CUST_IMG_URL = "https://www.takepoints.com/public/uploads/cgallery/customer";
	
	@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.verifycodenfc);
        manageMenu(0);
        
        ImageView imgNFCLogo = (ImageView)findViewById(R.id.imgNFCLogo);
        imgNFCLogo.setImageResource(R.drawable.nfccheckin);
        
        mAdapter = NfcAdapter.getDefaultAdapter(this);
		mPendingIntent = PendingIntent.getActivity( this, 0
								, new Intent(this , getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
								, 0);
		
		IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
		try{
			ndef.addDataType("*/*");
		} catch(MalformedMimeTypeException e){
			alert("MalformedMimeTypeException : " + e.getMessage());
		}

		mFilters = new IntentFilter[] { ndef, };
		mTechLists = new String[][] {
                new String[] { MifareClassic.class.getName(), NfcA.class.getName() }
		};
	}
	
	private void resolveIntent(Intent intent){
		String action = intent.getAction();
		if(NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
			Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
			if(tagFromIntent != null){
				try {
					//byte[] byte_id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
					/*
					Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
					Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
					r.play();
					*/
					String encryptedCode = read(tagFromIntent);
					new CheckInProcess(this).execute(encryptedCode);
/*					
					if(isAuthenFB()){
						final PostSocialDlg dlg = new PostSocialDlg(this);
						dlg.setTextToPost("ฉันอยู่ที่ร้าน   " + siteInfo.getSiteName());
						dlg.show();
						dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
					        public void onDismiss(DialogInterface dialog) {
								if(siteInfo != null && siteInfo.getErrorMsg() == null){
									if(!StringUtil.isEmpty(dlg.getTextToPost())){
										postToFacebook(  dlg.getTextToPost()
												 	   , siteInfo.getSiteName()
												 	   , "http://www.takepoints.com"
												 	   , "Takepoints ขอแนะนำ \"" + siteInfo.getSiteName() + "\""
												 	   , IMG_PATH + siteInfo.getPicName());
									}
								}
					        }
					    });
					}
*/
				} catch(IOException e){
					popup("IO Error : " + e.getMessage());
				} catch(FormatException e){
					popup("Format Error : " + e.getMessage());
				} catch(Exception e){
					popup("Error : " + e.getMessage());
				}
			}
		}
	}
	
	private String read(Tag tag) throws IOException, FormatException {
		StringBuilder result = new StringBuilder("");
		if(tag != null){
			MifareClassic mfc = MifareClassic.get(tag);
    		if(!mfc.isConnected()) mfc.connect();
    		boolean auth = mfc.authenticateSectorWithKeyA(1, SecurityUtil.getAuthenKey());
    		if(auth){
    			int bCount = mfc.getBlockCountInSector(1);
                int bIndex = 0;
                for(int i=0; i<bCount-1; i++){
                	bIndex = mfc.sectorToBlock(1);
                	if(!mfc.isConnected()) mfc.connect();
                    byte[] data = mfc.readBlock(bIndex + i);
                    
                    result.append(new String(data));
                }
    		} else{
    			popup("พบข้อผิดพลาด ไม่สามารถเช็คอินได้ !");
    		}
    		mfc.close();
		}
		return result.toString();
    }
	
	@Override
	public void onNewIntent(Intent intent){
    	super.onNewIntent(intent);
		resolveIntent(intent);
	}
	
	@Override
	public void onResume(){
		super.onResume();
		if(mAdapter != null){
			mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
		}
	}

	@Override
	public void onPause(){
		super.onPause();
        if(mAdapter != null){
            mAdapter.disableForegroundDispatch(this);
        }
	}
	
	protected void processTake(Context ctx){
		Intent homeInt = new Intent(this, Takepoints.class);
		startActivity(homeInt);
		finish();
	}
	
	private void alertResult(String msg, ReturnVal retVal){
		final String cid = retVal.getCustId();
		final String sname = retVal.getSiteName();
		final String simage = retVal.getSiteImage();
		final String usrId = retVal.getCustUserId();
		final String nfcId = retVal.getNfcId();
		final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
		/*
		if(isAuthenFB()){
			alertbox.setMessage(msg + "\n\nคุณต้องการ Post ไปยัง Facebook ด้วยหรือไม่ ?");
			alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dlgInf, int which){
					if(sname != null){
						postToFacebook(  "ฉันได้เช็คอินที่ " + sname
								 	   , sname
								 	   , "https://www.takepoints.com"
								 	   , "Takepoints ขอแนะนำ \"" + sname + "\""
								 	   , CUST_IMG_URL + usrId + "/" + "_thumb_" + simage );
						gotoPromotionList(cid, sname, nfcId);
					} else{
						alert("กรุณาลองเช็คอินใหม่อีกครั้ง ..");
					}
				}
			});
			alertbox.setNegativeButton("No", new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dlgInf, int which){
					gotoPromotionList(cid, sname, nfcId);
				}
			});
		} else{
			alertbox.setMessage(msg);
			alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dlgInf, int which){
					gotoPromotionList(cid, sname, nfcId);
				}
			});
		}*/
		alertbox.setMessage(msg);
		alertbox.setPositiveButton("ตกลง", new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dlgInf, int which){
				if(sname != null){
					gotoPromotionList(cid, sname, nfcId);
				} else{
					alert("กรุณาลองเช็คอินใหม่อีกครั้ง ..");
				}
			}
		});
		alertbox.show();
	}
	
	private final void gotoPromotionList(String custId, String siteName, String nfcId){
		if(!StringUtil.isEmpty(custId) && !StringUtil.isEmpty(siteName)){
			Intent detailInt = new Intent(this, TPPromotions.class);
			detailInt.putExtra("custId", custId);
			detailInt.putExtra("siteName", siteName);
			detailInt.putExtra("nfcId", nfcId);
			startActivityForResult(detailInt, 0);
		} else{
			Intent homeInt = new Intent(this, Takepoints.class);
			startActivityForResult(homeInt, 0);
		}
    }
	
	class CheckInProcess extends AsyncTask<String, Void, ReturnVal>{
		
		private Context context = null;
		private ProgressDialog progressDlg = null;
		
		CheckInProcess(Context context){
			this.context = context;
		}
		
		@Override
        protected void onPreExecute(){
            super.onPreExecute();
            progressDlg = ProgressDialog.show(context, "Takepoints.com", "กำลังเช็คอิน ...", true);
		}
		
		@Override
        protected ReturnVal doInBackground(String... params){
			String encryptedCode = params[0];
			if(encryptedCode == null || encryptedCode.trim().length() < 1){
				return null;
			}
			String nfcId = SecurityUtil.decrypt(encryptedCode, SecurityUtil.KEY_TYPE_PUBLIC);
			
			ReturnVal retVal = TPServices.checkin(getSharedIntValue(TPConst.PRF_MEMBER_ID), nfcId);
			if(retVal == null){
				retVal = new ReturnVal();
			}
			CustomerSiteInfo siteInfo = PublicServices.getSiteInfoByNfcId(nfcId);
			if(siteInfo != null){
				retVal.setCustId(siteInfo.getCustId());
				retVal.setSiteName(siteInfo.getCustName() + " (" + siteInfo.getSiteName() + ")");
				retVal.setSiteImage(siteInfo.getPicName());
				retVal.setCustUserId(siteInfo.getCustUserId());
			}
			retVal.setNfcId(nfcId);
			return retVal;
		}
		
		@Override
        protected void onPostExecute(ReturnVal retVal){
        	progressDlg.dismiss();
        	if(retVal != null){
        		alertResult("คุณได้เช็คอินที่ "+retVal.getSiteName(), retVal);
        	}
		}
	}
	
}
